package httputils

import (
	"bindolabs/new_monitor/tools/mylog"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"time"
)

// RequestParams 包含发送请求的所有参数
type RequestParams struct {
	URL      string
	Method   string
	Headers  map[string]string
	Params   map[string]string
	Body     map[string]interface{}
	BodyStr  string
	Timeout  time.Duration
	Mlog     *mylog.Log
	ShowInfo bool
}

// SendRequest 发送HTTP请求并返回响应体和错误
func (params *RequestParams) SendRequest() (string, error) {
	// 构建请求URL和参数
	Log := params.Mlog.NewLogger("")
	Log.Startf("SendRequest", "params:%v", params)
	reqURL, err := url.Parse(params.URL)
	if err != nil {
		return "", Log.Endf("invalid URL: %v", err.Error())
	}

	query := reqURL.Query()
	for k, v := range params.Params {
		query.Set(k, v)
	}
	reqURL.RawQuery = query.Encode()

	requestBody := []byte(params.BodyStr)
	if len(requestBody) <= 0 {
		// 将Body编码为JSON
		requestBody, err = json.Marshal(params.Body)
		if err != nil {
			return "", Log.Endln("failed to marshal request body:", err.Error())
		}
	}

	// 创建HTTP请求
	req, err := http.NewRequest(params.Method, reqURL.String(), bytes.NewBuffer(requestBody))
	if err != nil {
		return "", Log.Endln("failed to create request:", err.Error())
	}

	// 设置请求头
	for k, v := range params.Headers {
		req.Header.Set(k, v)
	}

	// 打印发送的请求信息
	if params.ShowInfo {
		Log.Printf("Request URL:%s Body: %s\n", reqURL.String(), string(requestBody))
		Log.Printf("Request URL: %s\n", reqURL.String())
		Log.Printf("Request Method: %s\n", params.Method)
		Log.Printf("Request Headers: %v\n", params.Headers)
	}

	// 发送请求
	client := &http.Client{
		Timeout: params.Timeout,
	}
	resp, err := client.Do(req)
	if err != nil {
		return "", Log.Endln("request failed:", err.Error())
	}
	defer resp.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", Log.Endln("failed to read response body:", err.Error())
	}

	// 检查HTTP状态码
	if resp.StatusCode < 200 || resp.StatusCode >= 300 {
		return "", Log.Endf("HTTP error: %s, body:[%s]", resp.Status, string(body))
	}
	Log.Endf("ok Res:%v", string(body))
	return string(body), nil
}

func RunRequest() {
	// 示例请求参数
	params := RequestParams{
		URL:    "https://api.example.com/data",
		Method: "POST",
		Headers: map[string]string{
			"Content-Type":  "application/json",
			"Authorization": "Bearer YOUR_TOKEN",
		},
		Params: map[string]string{
			"query": "golang",
		},
		Body: map[string]interface{}{
			"name": "Golang",
			"type": "Programming Language",
		},
		Timeout: 10 * time.Second,
	}

	// 发送请求并处理响应
	response, err := params.SendRequest()
	if err != nil {
		fmt.Printf("Error: %v\n", err)
	} else {
		fmt.Printf("Response: %s\n", response)
	}
}
